package com.ang.redisson.service;

import com.ang.redisson.utils.ReidssonUtil;
import org.redisson.api.RedissonClient;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class ProductService {
    @Autowired
    ReidssonUtil reidssonUtil;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 注释掉lock，和unlock，用jmeter测试，会出现超卖
     * @param productId
     * @return
     */
    public boolean createOrder(String productId){
        boolean result = false;

        String key = "redis_store_lock_" + productId;

        //加锁
        RLock rlock = reidssonUtil.lock(key);
        try{
            //原子递减
            int count = (Integer) redisTemplate.opsForValue().get(productId);
            if(count > 0){
                redisTemplate.opsForValue().decrement(productId);
                System.out.println(String.format("当前线程：%s，产品：%s，库存-1，剩余%s",Thread.currentThread().getName(),productId,count-1));
                result = true;
            }else{
                System.out.println("库存不足");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reidssonUtil.unlock(rlock);
        }

        return result;
    }
}
